package club.zhilin.guli.common.base.util;

import club.zhilin.guli.common.base.domain.JwtInfo;
import club.zhilin.guli.common.base.result.CommonResult;
import club.zhilin.guli.common.base.result.CommonResultCodeEnum;
import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * @author zhilin
 * @since 2022/2/26 0:22
 */
public class JwtUtil {

    /**
     * 覆盖公有构造器
     */
    private JwtUtil() {

    }

    public static final String APPLICATION_SECRET = "651F1A31DC169B8EF3D1591302160840";

    public static Key instance() {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        return new SecretKeySpec(DatatypeConverter.parseBase64Binary(APPLICATION_SECRET), signatureAlgorithm.getJcaName());
    }

    public static String createJwtToken(JwtInfo info, int expireTime) {
        return Jwts.builder().setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("guli-ucenter")
                .setIssuedAt(new Date())
                .setExpiration(DateTime.now().plusSeconds(expireTime).toDate())
                .claim("id", info.getId())
                .claim("nickname", info.getNickname())
                .claim("avatar", info.getAvatar())
                .signWith(SignatureAlgorithm.HS256, instance()).compact();
    }

    public static CommonResult<JwtInfo> requestGetMember(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            return CommonResult.failed(CommonResultCodeEnum.FETCH_USERINFO_ERROR);
        }
        Jws<Claims> claimsJws;
        try {
            claimsJws = Jwts.parser().setSigningKey(instance()).parseClaimsJws(token);
        } catch (ExpiredJwtException e) {
            return CommonResult.failed(CommonResultCodeEnum.MESSAGE_TOKEN_ALREADY_EXPIRE);
        }
        Claims body = claimsJws.getBody();
        return CommonResult.success(new JwtInfo(body.get("id").toString(), body.get("nickname").toString(), body.get("avatar").toString()));
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken token
     * @return
     */
    public static boolean checkJwtToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(instance()).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
